#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define BUFSIZE 4096
#define SLEN 81
void append(FILE* source, FILE* dest);
char *s_gets(char* st, int n);
int main(int argc, char* argv[])
{
	FILE *fa, *fs;
	int files = 0;
	int ch;
	char c;
	puts("Enter name of destination file:");
	if(argc != 3){
		fprintf(stderr, "can't open the file: %s\n", argv[0]);
		exit(EXIT_FAILURE);
	}
	if((fa = fopen(argv[1], "a+")) == NULL){
		fprintf(stderr, "open the file wrong");
		exit(EXIT_FAILURE);
	}
	if(setvbuf(fa, NULL, _IOFBF, BUFSIZE) != 0){
		fputs("Can't create output buffer\n", stderr);
		exit(EXIT_FAILURE);
	}
	puts("Enter the first soure file");
	while((c = getchar()) != EOF){
		getchar();
		if(strcmp(argv[1], argv[2]) == 0)
			fputs("Can't open the file to itself\n", stderr);
		else if ((fs = fopen(argv[2], "r")) == NULL)
			fprintf(stderr, "can't open the file %s\n", argv[2]);
		else{
			if(setvbuf(fs, NULL, _IOFBF, BUFSIZE) != 0)
			{
				fputs("Can't create input buffer\n", stderr);
				continue;
			}
			append(fs, fa);
			if(ferror(fs) != 0)
				fprintf(stderr, "Error in reading file %s.\n",argv[1]);
			if(ferror(fa) != 0)
				fprintf(stderr, "Error in reading file %s.\n",argv[2]);
			fclose(fs);
			files++;
			fprintf(stderr,"File %s appended.\n", argv[2]);
			puts("Next file :");
		}
	}
	rewind(fa);
	while((ch = getc(fa)) != EOF)
		putchar(ch);
	fclose(fa);
	
	return 0;
}
void append(FILE *source, FILE *dest)
{
	size_t bytes;
	static char temp[BUFSIZE];
	
	while((bytes = fread(temp, sizeof(char), BUFSIZE, source)) > 0)
		fwrite(temp, sizeof(char), bytes, dest);
}
char * s_gets(char * st, int n)
{
	char * ret_val;
	char *find;
	
	ret_val = fgets(st, n, stdin);
	if(ret_val)
	{
		find = strchr(st, '\n');
		if(find)
			*find = '\0';
		else
			while(getchar() != '\n')
				continue;
	}
	return ret_val;
}
